import React, { Component, Fragment } from 'react';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import moment from 'moment';
import { Map, Polyline, Markers } from 'react-amap';
import { connect } from 'dva';
import {
  Button,
  Row,
  Col,
  Card,
  Modal,
  Icon,
  List,
  Pagination,
  Popover,
  Alert,
} from 'antd';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import styles from './PostInfo.less';
import router from 'umi/router';
import blueMarker from '@/assets/location_blue.png';
import yellowMarker from '@/assets/location_yellow.png';

const { Description } = DescriptionList;

const getWindowWidth = () => window.innerWidth || document.documentElement.clientWidth;
const getWindowHeight = () => window.innerHeight || document.documentElement.clientHeight;

export default
@connect(({ post, loading }) => ({
  detail: post.detail,
  trackList: post.trackList,
  loading: loading.effects['post/fetchPost'],
}))
class PostInfo extends Component {
  state = {
    modalWidth: 520,
    modalHeight: 400,
    modalVisible: false,
    isWide: true,
  };

  columns = [
    {
      title: '用户昵称',
      dataIndex: 'log_username',
    },
    {
      title: '最近关怀地址',
      dataIndex: 'log_location',
    },
    {
      title: '最近关怀时间',
      dataIndex: 'log_created',
      render: val => <span>{moment.unix(val).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>关怀信息</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.handleRefresh();

    this.setModalSize();
    window.addEventListener('resize', this.setModalSize, { passive: true });

    this.mapEvents = {
      created: (ins) => {
        this.mapInstance = ins;
        setTimeout(() => {
          this.mapInstance.setFitView();
        }, 500);
      },
    };
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setModalSize);
    this.setModalSize.cancel();
  }

  @Bind()
  @Debounce(200)
  setModalSize() {
    const w = getWindowWidth();
    const h = getWindowHeight();
    this.setState({
      modalWidth: w - 40,
      modalHeight: h - 55 - 80,
      isWide: w > 600,
    });
  }

  handleCancel = () => {
    this.setState({modalVisible: false});
  }

  handleChangeMobilePage = (current) => {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'post/fetch',
      payload: {
        id: params.id,
        p: current,
      },
    });
  }

  handleRefresh = () => {
    const { dispatch, match } = this.props;
    const { params } = match;
    dispatch({
      type: 'post/fetchPost',
      payload: {
        id: params.id,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, match } = this.props;
    const { params } = match;

    dispatch({
      type: 'post/fetchPost',
      payload: {
        id: params.id,
        p: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  showPreview = () => {
    const {protocol, hostname} = window.location;
    const {detail} = this.props;
    const previewUrl = `${protocol}//${hostname}/track/index.php/Index/${detail.post_id}`;
    window.open(previewUrl, '_blank');
  }
  
  renderTerm = (val) => <span className={styles.descTerm}>{val}</span>;

  render() {
    const { modalVisible, modalWidth, modalHeight, isWide } = this.state;
    const { detail, loading, trackList } = this.props;

    const path = [];
    trackList.forEach(item=> {
      if(item.log_position) {
        const lnglat = JSON.parse(item.log_position);
        path.push({
          ...item,
          longitude: lnglat[0],
          latitude: lnglat[1],
        });
      }
    });

    const markers = path.map((item, index) => {
      return {
        position: item,
        last: index === path.length - 1,
        location: item.log_location,
        created: item.log_created,
      }
    });

    if(path.length && this.mapInstance) {
      setTimeout(() => {
        this.mapInstance.setFitView();
      }, 500);
    } 

    const trackData = detail.track || {};

    const action = (
      <Fragment>
        <Button className={styles.detailButton} onClick={()=>{router.push('/list');}}>返回</Button>
        <Button className={styles.detailButton} onClick={this.showPreview} type="primary"><Icon type="eye" /> 预览并转发</Button>
      </Fragment>
    );

    const redpacketDesc = detail.post_type === '0' ? [
      <Description key="0" term={this.renderTerm('红包个数')}><span className={styles.descText}>{detail.post_redpacket_num}</span></Description>,
      <Description key="1" term={this.renderTerm('已领红包')}><span className={styles.descText}>0</span></Description>,
      <Description key="2" term={this.renderTerm('红包总金额')}><span className={styles.descText}>{detail.post_redpacket_price}</span></Description>,
      <Description key="3" term={this.renderTerm('领取规则')}><span className={styles.descText}>{detail.post_redpacket_rule === '1' ? '每个红包金额随机' : '每个红包金额相等'}</span></Description>,
    ] : [];
    const bodyDesc = detail.post_type !== '0' ? [
      <Description key="4" term={this.renderTerm('内页标题')}><span className={styles.descText}>{detail.post_body_title}</span></Description>,
      <Description key="5" term={this.renderTerm('内页描述')}><span className={styles.descText}>{detail.post_body_desc}</span></Description>
    ] : [];

    const extra = (
      <Row>
        <Col xs={12} sm={12}>
          <div className={styles.textSecondary}>文章类型</div>
          <div className={styles.heading}>{detail.post_type_str}</div>
        </Col>
        <Col xs={12} sm={12}>
          <div className={styles.textSecondary}>关怀人次</div>
          <div className={styles.heading}>{detail.post_track_num || 0}</div>
        </Col>
      </Row>
    );

    const {protocol, hostname} = window.location;
    const thumbUrl = `${protocol}//${hostname}/track/Uploads/thumb/${detail.post_thumb_url}`;

    return (
      <PageHeaderWrapper>
        <Card
          bordered={false}
          title="发布详情"
          extra={
            <Button size="large" onClick={()=>{router.push('/list');}}>返回</Button>}
        >
          <DescriptionList className={styles.descList} col={1} layout="vertical">
            <Description term={this.renderTerm('主标题')}><span className={styles.descText}>{detail.post_title}</span></Description>
            <Description term={this.renderTerm('副标题')}><span className={styles.descText}>{detail.post_subtitle}</span></Description>
            <Description term={this.renderTerm('缩略图')}><img alt="" src={thumbUrl} className={styles.thumb} /></Description>
            {bodyDesc}
            {redpacketDesc}
          </DescriptionList>
          {detail.post_status == 0 ? 
            <Button size="large" style={{marginTop: 12, marginRight: 8}} className={styles.detailButton} onClick={this.showPreview} type="primary"><Icon type="eye" /> 预览并转发</Button> : 
            <Alert message="红包金额未充值，不能转发" type="error" showIcon />
          }
        </Card>
      </PageHeaderWrapper>
    );
  }
}
